import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';

import 'core/service_locator.dart';
import 'core/error_handler.dart';
import 'pages_adapter.dart';
import 'models/user_info.dart';
import 'AI/smart_floating_ball_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  try {
    await _initializeApp();
    
    final isFirstRun = await _checkFirstRun();
    runApp(PatchouliKnowledgeApp(isFirstRun: isFirstRun));
    
  } catch (e) {
    print('应用启动失败: $e');
    runApp(_buildErrorApp(e));
  }
}

/// 初始化应用
Future<void> _initializeApp() async {
  print('🚀 开始初始化应用...');
  
  // 初始化所有服务
  await ServiceLocator.initializeServices();
  print('✅ 服务初始化完成');
  
  print('🎉 应用初始化完成');
}

/// 检查是否首次运行
Future<bool> _checkFirstRun() async {
  try {
    final userInfo = await ServiceLocator.fileServe.readUserInfo();
    return userInfo == null;
  } catch (e) {
    return true; // 出错时默认为首次运行
  }
}

/// 构建错误界面
Widget _buildErrorApp(dynamic error) {
  return MaterialApp(
    title: '知拾',
    home: Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red),
            SizedBox(height: 16),
            Text('应用初始化失败', style: TextStyle(fontSize: 24)),
            SizedBox(height: 8),
            Text('错误信息: $error', style: TextStyle(fontSize: 14)),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: () => main(),
              child: Text('重试'),
            ),
          ],
        ),
      ),
    ),
  );
}

class PatchouliKnowledgeApp extends StatelessWidget {
  final bool isFirstRun;
  
  const PatchouliKnowledgeApp({
    Key? key,
    required this.isFirstRun,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '知拾',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: isFirstRun 
        ? WelcomePageAdapter(
            llm: ServiceLocator.llm,
            difyKnowledge: ServiceLocator.difyKnowledge,
            fileServe: ServiceLocator.fileServe,
          )
        : MainNavigationPage(),
    );
  }
}

class MainNavigationPage extends StatefulWidget {
  const MainNavigationPage({Key? key}) : super(key: key);

  @override
  _MainNavigationPageState createState() => _MainNavigationPageState();
}

class _MainNavigationPageState extends State<MainNavigationPage>
    with TickerProviderStateMixin {
  int _selectedIndex = 0;
  late List<Widget> _pages;
  late UserInfo userInfo;
  bool _isLoading = true;
  PageController? _pageController;
  AnimationController? _animationController;
  Animation<double>? _fadeAnimation;
  
  // 全局悬浮球事件监听
  StreamSubscription<SmartFloatingBallEvent>? _floatingBallEventSubscription;

  @override
  void initState() {
    super.initState();
    _initializeControllers();
    _loadUserInfo();
    _setupGlobalFloatingBallListener();
  }

  @override
  void dispose() {
    _pageController?.dispose();
    _animationController?.dispose();
    _floatingBallEventSubscription?.cancel();
    super.dispose();
  }

  void _initializeControllers() {
    _pageController = PageController();
    _animationController = AnimationController(
      duration: Duration(milliseconds: 300),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController!,
      curve: Curves.easeInOutCubic,
    ));
    _animationController!.forward();
  }
  
  /// 设置全局悬浮球事件监听
  void _setupGlobalFloatingBallListener() {
    try {
      _floatingBallEventSubscription = SmartFloatingBallService.eventStream.listen(
        _handleGlobalFloatingBallEvent,
        onError: (error) => print('全局悬浮球事件流错误: $error'),
      );
    } catch (e) {
      print('设置全局悬浮球事件监听失败: $e');
    }
  }
  
  /// 处理全局悬浮球事件
  void _handleGlobalFloatingBallEvent(SmartFloatingBallEvent event) {
    if (!mounted) return;
    
    switch (event.type) {
      case SmartFloatingBallEventType.screenshotSuccessWithNavigation:
        final imagePath = event.data?['imagePath'];
        final navigateToUpload = event.data?['navigateToUpload'] ?? false;
        
        if (navigateToUpload && imagePath != null) {
          ErrorHandler.showSuccessSnackBar(context, '截图成功，正在打开上传页面...');
          _navigateToUploadWithImage(imagePath);
        }
        break;
        
      case SmartFloatingBallEventType.screenshotResult:
        final success = event.data?['success'] ?? false;
        final error = event.data?['error'];
        
        if (success) {
          ErrorHandler.showSuccessSnackBar(context, '截图处理完成');
        } else {
          ErrorHandler.showErrorSnackBar(context, AppError(
            type: AppErrorType.ai,
            message: '截图处理失败：${error ?? "未知错误"}',
          ));
        }
        break;
        
      default:
        break;
    }
  }
  
  /// 导航到上传页面（带截图）
  void _navigateToUploadWithImage(String imagePath) {
    Navigator.push(
      context,
      MaterialPageRoute(
        settings: RouteSettings(name: '/upload'),
        builder: (context) => UploadPageAdapter(
          llm: ServiceLocator.llm,
          fileServe: ServiceLocator.fileServe,
          difyKnowledge: ServiceLocator.difyKnowledge,
          appDataDir: ServiceLocator.fileServe.appDataDir,
          preSelectedImagePath: imagePath,
          screenShotServe: ServiceLocator.screenShotServe,
        ),
      ),
    );
  }

  Future<void> _loadUserInfo() async {
    try {
      final userInfoData = await ServiceLocator.fileServe.readUserInfo();
      setState(() {
        userInfo = UserInfo.fromJson(userInfoData!);
        _initPages();
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        userInfo = UserInfo(nickname: '', identityTags: []);
        _initPages();
        _isLoading = false;
      });
    }
  }

  void _initPages() {
    _pages = [
      HomePageAdapter(
        llm: ServiceLocator.llm,
        difyKnowledge: ServiceLocator.difyKnowledge,
        userInfo: userInfo,
        fileServe: ServiceLocator.fileServe,
      ),
      ChatPageAdapter(
        llm: ServiceLocator.llm,
        difyKnowledge: ServiceLocator.difyKnowledge,
        userInfo: userInfo,
        fileServe: ServiceLocator.fileServe,
      ),
      IdentityPageAdapter(
        userInfo: userInfo,
        onUpdateUserInfo: _updateUserInfo,
        fileServe: ServiceLocator.fileServe,
      ),
      SettingPageAdapter(
        llm: ServiceLocator.llm,
        difyKnowledge: ServiceLocator.difyKnowledge,
        fileServe: ServiceLocator.fileServe,
      ),
    ];
  }

  void _updateUserInfo(UserInfo newUserInfo) {
    setState(() {
      userInfo = newUserInfo;
      _initPages();
    });
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
    _pageController?.animateToPage(
      index,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOutCubic,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return Scaffold(
      body: FadeTransition(
        opacity: _fadeAnimation!,
        child: PageView(
          controller: _pageController,
          children: _pages,
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '主页'),
          BottomNavigationBarItem(icon: Icon(Icons.chat), label: '聊天'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '身份'),
          BottomNavigationBarItem(icon: Icon(Icons.settings), label: '设置'),
        ],
        currentIndex: _selectedIndex,
        type: BottomNavigationBarType.fixed,
        onTap: _onItemTapped,
      ),
    );
  }
}
